import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
    Box,
    Container,
    Paper,
    Typography,
    Button,
    Divider,
    Grid,
    Avatar,
    Chip,
    LinearProgress,
    CircularProgress,
    IconButton,
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import EditIcon from '@mui/icons-material/Edit';
import ShareIcon from '@mui/icons-material/Share';
import DownloadIcon from '@mui/icons-material/Download';
import { useAuth } from '../contexts/AuthContext';

const ResumePreview = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const { isAuthenticated } = useAuth();
    const [loading, setLoading] = useState(true);
    const [resume, setResume] = useState(null);

    // 加载简历数据
    useEffect(() => {
        const loadResumeData = async () => {
            try {
                // 在实际应用中，这应该是一个API调用
                // 这里我们模拟API调用
                setTimeout(() => {
                    const mockResume = {
                        id: id,
                        title: '软件工程师简历',
                        template: 'modern',
                        personalInfo: {
                            name: '张三',
                            email: 'zhangsan@example.com',
                            phone: '13800138000',
                            location: '北京市',
                            title: '高级前端开发工程师',
                            summary: '5年前端开发经验，专注于React和Vue框架，有丰富的大型应用开发经验。',
                        },
                        education: [
                            {
                                id: '1',
                                institution: '北京大学',
                                degree: '计算机科学学士',
                                startDate: '2014-09',
                                endDate: '2018-07',
                                description: '主修计算机科学与技术，GPA 3.8/4.0'
                            }
                        ],
                        experience: [
                            {
                                id: '1',
                                company: 'ABC科技有限公司',
                                position: '前端开发工程师',
                                startDate: '2018-08',
                                endDate: '2021-12',
                                description: '负责公司主要产品的前端开发，使用React框架构建用户界面，实现响应式设计。'
                            },
                            {
                                id: '2',
                                company: 'XYZ互联网公司',
                                position: '高级前端开发工程师',
                                startDate: '2022-01',
                                endDate: '至今',
                                description: '负责团队技术选型和架构设计，开发和维护公司核心产品，指导初级开发人员。'
                            }
                        ],
                        skills: [
                            { id: '1', name: 'React', level: 90 },
                            { id: '2', name: 'JavaScript', level: 85 },
                            { id: '3', name: 'CSS', level: 80 },
                            { id: '4', name: 'Node.js', level: 75 },
                            { id: '5', name: 'Vue.js', level: 70 },
                            { id: '6', name: 'TypeScript', level: 65 }
                        ],
                        projects: [
                            {
                                id: '1',
                                name: '电商平台重构',
                                description: '使用React和TypeScript重构公司电商平台，提升了30%的页面加载速度。'
                            },
                            {
                                id: '2',
                                name: '数据可视化仪表板',
                                description: '开发了一个实时数据可视化仪表板，帮助业务团队更好地理解用户行为。'
                            }
                        ],
                        languages: [
                            { id: '1', name: '中文', level: '母语' },
                            { id: '2', name: '英语', level: '流利' }
                        ],
                    };

                    setResume(mockResume);
                    setLoading(false);
                }, 1000);
            } catch (error) {
                console.error('加载简历数据失败:', error);
                setLoading(false);
            }
        };

        loadResumeData();
    }, [id]);

    // 返回上一页
    const handleBack = () => {
        navigate(-1);
    };

    // 编辑简历
    const handleEdit = () => {
        navigate(`/editor/${id}`);
    };

    // 分享简历
    const handleShare = () => {
        navigate(`/share/${id}`);
    };

    // 下载简历为PDF
    const handleDownload = () => {
        alert('PDF下载功能正在开发中');
        // 在实际应用中，这里会调用PDF生成和下载的逻辑
    };

    // 如果正在加载，显示加载指示器
    if (loading) {
        return (
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '80vh' }}>
                <CircularProgress />
            </Box>
        );
    }

    // 如果简历不存在
    if (!resume) {
        return (
            <Container maxWidth="md" sx={{ mt: 4, mb: 8, textAlign: 'center' }}>
                <Typography variant="h4" gutterBottom>
                    简历不存在或已被删除
                </Typography>
                <Button variant="contained" onClick={() => navigate('/dashboard')} sx={{ mt: 2 }}>
                    返回仪表盘
                </Button>
            </Container>
        );
    }

    return (
        <Container maxWidth="md" sx={{ mt: 4, mb: 8 }}>
            {/* 预览头部 */}
            <Box sx={{ mb: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <IconButton onClick={handleBack} sx={{ mr: 2 }}>
                        <ArrowBackIcon />
                    </IconButton>
                    <Typography variant="h5" component="h1">
                        {resume.title}
                    </Typography>
                </Box>
                <Box>
                    {isAuthenticated && (
                        <Button
                            variant="outlined"
                            startIcon={<EditIcon />}
                            onClick={handleEdit}
                            sx={{ mr: 2 }}
                        >
                            编辑
                        </Button>
                    )}
                    <Button
                        variant="outlined"
                        startIcon={<ShareIcon />}
                        onClick={handleShare}
                        sx={{ mr: 2 }}
                    >
                        分享
                    </Button>
                    <Button
                        variant="contained"
                        startIcon={<DownloadIcon />}
                        onClick={handleDownload}
                    >
                        下载PDF
                    </Button>
                </Box>
            </Box>

            {/* 简历内容 */}
            <Paper
                elevation={3}
                sx={{
                    p: 4,
                    maxWidth: '800px',
                    margin: '0 auto',
                    backgroundColor: '#fff',
                }}
            >
                {/* 个人信息部分 */}
                <Box sx={{ mb: 4, textAlign: 'center' }}>
                    <Typography variant="h4" component="h1" gutterBottom>
                        {resume.personalInfo.name}
                    </Typography>
                    <Typography variant="h6" color="primary" gutterBottom>
                        {resume.personalInfo.title}
                    </Typography>
                    <Box sx={{ display: 'flex', justifyContent: 'center', flexWrap: 'wrap', gap: 2, mt: 2 }}>
                        <Typography variant="body2">
                            📧 {resume.personalInfo.email}
                        </Typography>
                        <Typography variant="body2">
                            📱 {resume.personalInfo.phone}
                        </Typography>
                        <Typography variant="body2">
                            📍 {resume.personalInfo.location}
                        </Typography>
                    </Box>
                </Box>

                <Divider sx={{ mb: 3 }} />

                {/* 个人简介 */}
                {resume.personalInfo.summary && (
                    <Box sx={{ mb: 4 }}>
                        <Typography variant="h6" gutterBottom sx={{ color: 'primary.main' }}>
                            个人简介
                        </Typography>
                        <Typography variant="body1" paragraph>
                            {resume.personalInfo.summary}
                        </Typography>
                    </Box>
                )}

                {/* 工作经验 */}
                {resume.experience && resume.experience.length > 0 && (
                    <Box sx={{ mb: 4 }}>
                        <Typography variant="h6" gutterBottom sx={{ color: 'primary.main' }}>
                            工作经验
                        </Typography>
                        {resume.experience.map((exp) => (
                            <Box key={exp.id} sx={{ mb: 2 }}>
                                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                                    <Typography variant="subtitle1" fontWeight="bold">
                                        {exp.company}
                                    </Typography>
                                    <Typography variant="body2" color="text.secondary">
                                        {exp.startDate} - {exp.endDate}
                                    </Typography>
                                </Box>
                                <Typography variant="subtitle2" color="primary" gutterBottom>
                                    {exp.position}
                                </Typography>
                                <Typography variant="body2" paragraph>
                                    {exp.description}
                                </Typography>
                            </Box>
                        ))}
                    </Box>
                )}

                {/* 教育经历 */}
                {resume.education && resume.education.length > 0 && (
                    <Box sx={{ mb: 4 }}>
                        <Typography variant="h6" gutterBottom sx={{ color: 'primary.main' }}>
                            教育经历
                        </Typography>
                        {resume.education.map((edu) => (
                            <Box key={edu.id} sx={{ mb: 2 }}>
                                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                                    <Typography variant="subtitle1" fontWeight="bold">
                                        {edu.institution}
                                    </Typography>
                                    <Typography variant="body2" color="text.secondary">
                                        {edu.startDate} - {edu.endDate}
                                    </Typography>
                                </Box>
                                <Typography variant="subtitle2" color="primary" gutterBottom>
                                    {edu.degree}
                                </Typography>
                                <Typography variant="body2" paragraph>
                                    {edu.description}
                                </Typography>
                            </Box>
                        ))}
                    </Box>
                )}

                {/* 技能 */}
                {resume.skills && resume.skills.length > 0 && (
                    <Box sx={{ mb: 4 }}>
                        <Typography variant="h6" gutterBottom sx={{ color: 'primary.main' }}>
                            技能
                        </Typography>
                        <Grid container spacing={2}>
                            {resume.skills.map((skill) => (
                                <Grid item xs={12} sm={6} key={skill.id}>
                                    <Box sx={{ mb: 1 }}>
                                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                            <Typography variant="body1">{skill.name}</Typography>
                                            <Typography variant="body2">{skill.level}%</Typography>
                                        </Box>
                                        <LinearProgress
                                            variant="determinate"
                                            value={skill.level}
                                            sx={{ height: 6, borderRadius: 3 }}
                                        />
                                    </Box>
                                </Grid>
                            ))}
                        </Grid>
                    </Box>
                )}

                {/* 项目经验 */}
                {resume.projects && resume.projects.length > 0 && (
                    <Box sx={{ mb: 4 }}>
                        <Typography variant="h6" gutterBottom sx={{ color: 'primary.main' }}>
                            项目经验
                        </Typography>
                        {resume.projects.map((project) => (
                            <Box key={project.id} sx={{ mb: 2 }}>
                                <Typography variant="subtitle1" fontWeight="bold">
                                    {project.name}
                                </Typography>
                                <Typography variant="body2" paragraph>
                                    {project.description}
                                </Typography>
                            </Box>
                        ))}
                    </Box>
                )}

                {/* 语言 */}
                {resume.languages && resume.languages.length > 0 && (
                    <Box>
                        <Typography variant="h6" gutterBottom sx={{ color: 'primary.main' }}>
                            语言
                        </Typography>
                        <Grid container spacing={2}>
                            {resume.languages.map((language) => (
                                <Grid item key={language.id}>
                                    <Chip
                                        label={`${language.name}: ${language.level}`}
                                        variant="outlined"
                                    />
                                </Grid>
                            ))}
                        </Grid>
                    </Box>
                )}
            </Paper>
        </Container>
    );
};

export default ResumePreview; 